﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace bvsoftware.bvtransfer.Core
{
    class StoreDataManager
    {
        public static string StorageFolder()
        {
            return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),"BV Software\\BV Transfer");
        }

        public static string StorageFileName()
        {
            return Path.Combine(StorageFolder(), "StoreData.txt");
        }
        
        public static List<StoreData> FindAll()
        {
            List<StoreData> result = new List<StoreData>();            
            LoadFromFile(StorageFileName(),result);            
            return result;
        }

        public static void LoadFromFile(string fileName, List<StoreData> result)
        {
            if (File.Exists(fileName))
            {
                string[] lines = File.ReadAllLines(fileName);
                foreach (string l in lines)
                {
                    result.Add(LoadLine(l));
                }
            }
        }
        
        public static StoreData LoadLine(string line)
        {
            StoreData result = new StoreData();
            string[] parts = line.Split('\t');
            if (parts.Length > 0)
            {
                result.Id = parts[0];
            }
            if (parts.Length > 1)
            {
                result.FriendlyName = parts[1];
            }
            if (parts.Length > 2)
            {
                result.StoreUrl = parts[2];
            }
            if (parts.Length > 3)
            {
                result.Username = parts[3];
            }
            if (parts.Length > 4)
            {
                result.Password = parts[4];
            }

            return result;
        }

        public static string CreateLine(StoreData s)
        {
            string result = string.Empty;
            result = s.Id 
                    + "\t" + s.FriendlyName 
                    + "\t" + s.StoreUrl 
                    + "\t" + s.Username 
                    + "\t" + s.Password 
                    + System.Environment.NewLine;
            return result;
        }

        public static void SaveAll(List<StoreData> stores)
        {
            SaveToFile(StorageFileName(), stores);
        }

        public static void SaveToFile(string filename, List<StoreData> stores)
        {
            StringBuilder sb = new StringBuilder();

            if (stores != null)
            {
                foreach (StoreData s in stores)
                {
                    sb.Append(CreateLine(s));
                }
            }
            Directory.CreateDirectory(StorageFolder());
            File.WriteAllText(filename, sb.ToString(), System.Text.Encoding.UTF8);
        }

    }
}
